<template>
  <div class="reservation-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>预订管理</h2>
          <div class="header-controls">
            <el-select
              v-model="selectedStatus"
              placeholder="请选择订单状态"
              clearable
              size="small"
              style="width: 180px; margin-right: 10px"
            >
              <el-option label="全部" value="" />
              <el-option label="待支付" value="PENDING_PAYMENT" />
              <el-option label="已确认" value="CONFIRMED" />
              <el-option label="支付超时" value="PAYMENT_EXPIRED" />
              <el-option label="取消申请中" value="CANCELLATION_REQUESTED" />
              <el-option label="已取消" value="CANCELLED" />
              <el-option label="已排期" value="SCHEDULED" />
              <el-option label="使用中" value="IN_USE" />
              <el-option label="已完成" value="COMPLETED" />
            </el-select>
            <el-button type="primary" @click="fetchReservations">刷新数据</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredReservations" style="width: 100%" border stripe v-loading="loading">
        <el-table-column prop="bookingId" label="预订ID" width="80" sortable />
        <el-table-column prop="roomId" label="会议室ID" width="100" sortable />
        <el-table-column prop="userId" label="用户ID" width="100" sortable />
        <el-table-column label="开始时间" width="180" sortable>
          <template #default="scope">
            {{ new Date(scope.row.startTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180" sortable>
          <template #default="scope">
            {{ new Date(scope.row.endTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-space>
              <el-button type="primary" size="small" @click="handleViewDetails(scope.row)">
                查看详情
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailsVisible" title="预订详情" width="50%">
      <div v-if="selectedReservation" class="reservation-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="预订ID">{{
            selectedReservation.bookingId
          }}</el-descriptions-item>
          <el-descriptions-item label="会议室名称">{{
            selectedReservation.roomName
          }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{
            selectedReservation.username
          }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{
            selectedReservation.fullName
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
            selectedReservation.phone
          }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ new Date(selectedReservation.startTime).toLocaleString() }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{ new Date(selectedReservation.endTime).toLocaleString() }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedReservation.status)">
              {{ getStatusLabel(selectedReservation.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const reservations = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailsVisible = ref(false)
const selectedReservation = ref(null)
const selectedStatus = ref('')

// 添加分页计算属性
const filteredReservations = computed(() => {
  let result = reservations.value

  // 状态过滤
  if (selectedStatus.value) {
    result = result.filter((r) => r.status === selectedStatus.value)
  }

  // 更新总数
  total.value = result.length

  // 分页处理
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value

  return result.slice(startIndex, endIndex)
})

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    PENDING_PAYMENT: 'warning',
    CONFIRMED: 'success',
    PAYMENT_EXPIRED: 'danger',
    CANCELLATION_REQUESTED: 'warning',
    CANCELLED: 'info',
    SCHEDULED: 'primary',
    IN_USE: 'success',
    COMPLETED: 'primary',
  }
  return types[status] || 'info'
}

// 获取状态中文标签
const getStatusLabel = (status) => {
  const labels = {
    PENDING_PAYMENT: '待支付',
    CONFIRMED: '已确认',
    PAYMENT_EXPIRED: '支付超时',
    CANCELLATION_REQUESTED: '取消申请中',
    CANCELLED: '已取消',
    SCHEDULED: '已排期',
    IN_USE: '使用中',
    COMPLETED: '已完成',
  }
  return labels[status] || status
}

// 查看详情
const handleViewDetails = (reservation) => {
  selectedReservation.value = reservation
  detailsVisible.value = true
}

// 获取预订列表
const fetchReservations = async () => {
  loading.value = true
  try {
    const response = await axios.get(
      'http://localhost:8080/api/reservations/reservations-with-details'
    )
    reservations.value = response.data
  } catch (error) {
    console.error('Error fetching reservations:', error)
    ElMessage.error('获取预订数据失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页显示数量时重置为第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

onMounted(fetchReservations)
</script>

<style scoped>
.reservation-management {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.reservation-details {
  padding: 20px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-tag) {
  min-width: 60px;
  text-align: center;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>
